﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using Microsoft.Practices.Unity;

namespace WDA.Core.DynamicReconfiguration
{
   internal class ConfigVersionMessageInspector : IClientMessageInspector, IDispatchMessageInspector
   {
      [Dependency(WDAContainerNames.PersistentInternalContainerName)]
      public IUnityContainer Container { get; set; }

      #region IClientMessageInspector Members
      public void AfterReceiveReply(ref Message reply, object correlationState)
      {         
         throw new NotImplementedException();
      }
      public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
      {
         RuntimeVersion currentVersion = Container.Resolve<RuntimeVersion>();
         ConfigVersionHeader versionHeader = new ConfigVersionHeader(currentVersion.VersionNumber);
         request.Headers.Add(versionHeader);
         return null;
      }
      #endregion

      #region IDispatchMessageInspector Members
      public object AfterReceiveRequest(ref Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
      {
         ConfigVersionHeader versionHeader = ConfigVersionHeader.ReadFrom(request);
         if (versionHeader != null)
         {
            RuntimeVersion currentVersion = Container.Resolve<RuntimeVersion>();
            if (versionHeader.VersionNumber < currentVersion.VersionNumber)
            {
               throw new InvalidOperationException();
            }
            if (versionHeader.VersionNumber > currentVersion.VersionNumber)
            {
               throw new InvalidOperationException();
            }
         }
         return null;
      }
      public void BeforeSendReply(ref Message reply, object correlationState)
      {
         throw new NotImplementedException();
      }
      #endregion
   }
}
